# To change this template, choose Tools | Templates
# and open the template in the editor.

require 'rubygems'
require 'dbf'
require 'persona'
require 'garantia'
require 'empleado'
require 'local'
require 'credito'
require 'cuota'
require 'time'

ActiveRecord::Base.establish_connection(
  :adapter => "postgresql",
  :database => "bernardoCreditos_dev",
  :username => "postgres",
  :password => "postgres",
  :host=> "localhost",
  :port=> "5432",
  :pool=> "5",
  :encoding => "utf8"
)

ActiveSupport::Inflector.inflections do |inflect|
  inflect.plural /([aeiou])([A-Z]|_|$)/, '\1s\2'
  inflect.plural /([rlnd])([A-Z]|_|$)/, '\1es\2'
  inflect.singular /([aeiou])s([A-Z]|_|$)/, '\1\2'
  inflect.singular /([rlnd])es([A-Z]|_|$)/, '\1\2'
  inflect.irregular 'user', 'users'
  inflect.irregular 'account', 'accounts'
  inflect.irregular 'password', 'passwords'
  inflect.irregular 'session', 'sessions'
end

#Se limpian las tablas releacionadas con la migracion
Cuota.delete_all

#cargo archivo
tabla_cuotas = DBF::Table.new("C:/cuotas.dbf")

cuotas_total = 0
cuotas_error = 0

puts "Arranca: #{Time.now}"
tabla_cuotas.each do |cuota|
  begin
    cuotas_total += 1
    persona = Persona.find(:first, :conditions => "cedula='#{cuota.ci}'")
    if persona.nil?
      puts"No encontre la persona con cedula #{cuota.ci}"
    end

    credito = Credito.find(:first, :conditions => "persona_id='#{persona.id}' and vale_temp = #{cuota.vale}")
    if credito.nil?
      puts"No encontre el credito con cedula #{persona.cedula} y vale #{cuota.vale}"
    end
    
    cuota_nueva = Cuota.new do |c|
      c.credito = credito
      c.numero_cuota = cuota.cuota
      c.fecha_vencimiento = cuota.venc
      c.fecha_pago = cuota.pago
      c.save
    end

    if cuota_nueva.nil?
      puts "No se creo la cuota (ci, vale) = #{persona.cedula} y vale #{cuota.vale}"
    end
    
  rescue Exception => exc
    cuotas_error += 1
    STDERR.puts "CUOTA (ci,vale) = (#{cuota.ci},#{cuota.vale}) - Error al dar de alta: #{exc.message}"
  end
end

puts "Creditos procesados: #{cuotas_total}"
puts "Creditos con ERRORES: #{cuotas_error}"
puts "Termino: #{Time.now}"